/*
 *  NFCSigning - Open source library for signing/validation of NDEF messages
 *  Copyright (C) 2009-2010 The NFCSigning Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */
package hello;

import javax.microedition.contactless.ContactlessException;
import javax.microedition.contactless.DiscoveryManager;
import javax.microedition.contactless.TargetListener;
import javax.microedition.contactless.TargetProperties;
import javax.microedition.contactless.TargetType;
import javax.microedition.contactless.ndef.NDEFMessage;
import javax.microedition.contactless.ndef.NDEFRecordType;
import javax.microedition.contactless.ndef.NDEFTagConnection;
import javax.microedition.io.Connector;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author emarkki
 */
public class HelloMIDlet extends MIDlet implements CommandListener, TargetListener {

    /**
     * SmartPoster containing URL and Sig.
     * Created using com.ericsson.nfc.signingprototypelibrary1 code
     */
    private static byte[] msgSpUrlSig1 = { 
        (byte) 217, 
        (byte) 2,         (byte) 125,         (byte) 0,         (byte) 83, 
        (byte) 112,         (byte) 153,         (byte) 1,         (byte) 26, 
        (byte) 0,         (byte) 85,         (byte) 0,         (byte) 104, 
        (byte) 116,         (byte) 116,         (byte) 112,         (byte) 58, 
        (byte) 47,         (byte) 47,         (byte) 119,         (byte) 119, 
        (byte) 119,         (byte) 46,         (byte) 109,         (byte) 97, 
        (byte) 114,         (byte) 107,         (byte) 117,         (byte) 115, 
        (byte) 112,         (byte) 97,         (byte) 103,         (byte) 101, 
        (byte) 46,         (byte) 99,         (byte) 111,         (byte) 109, 
        (byte) 89,         (byte) 3,         (byte) 86,         (byte) 1, 
        (byte) 83,         (byte) 105,         (byte) 103,         (byte) 9, 
        (byte) 1,         (byte) 1,         (byte) 0,         (byte) 64, 
        (byte) 111,         (byte) 19,         (byte) 169,         (byte) 86, 
        (byte) 223,         (byte) 144,         (byte) 99,         (byte) 226, 
        (byte) 72,         (byte) 94,         (byte) 9,         (byte) 247, 
        (byte) 141,         (byte) 241,         (byte) 41,         (byte) 148, 
        (byte) 177,         (byte) 94,         (byte) 103,         (byte) 90, 
        (byte) 158,         (byte) 103,         (byte) 59,         (byte) 125, 
        (byte) 196,         (byte) 213,         (byte) 105,         (byte) 24, 
        (byte) 188,         (byte) 35,         (byte) 18,         (byte) 18, 
        (byte) 200,         (byte) 52,         (byte) 231,         (byte) 186, 
        (byte) 74,         (byte) 32,         (byte) 214,         (byte) 246, 
        (byte) 60,         (byte) 180,         (byte) 140,         (byte) 242, 
        (byte) 250,         (byte) 62,         (byte) 56,         (byte) 71, 
        (byte) 25,         (byte) 190,         (byte) 231,         (byte) 226, 
        (byte) 209,         (byte) 146,         (byte) 30,         (byte) 152, 
        (byte) 115,         (byte) 244,         (byte) 18,         (byte) 213, 
        (byte) 192,         (byte) 202,         (byte) 28,         (byte) 99, 
        (byte) 1,         (byte) 0,         (byte) 15,         (byte) 42, 
        (byte) 42,         (byte) 67,         (byte) 69,         (byte) 82, 
        (byte) 84,         (byte) 73,         (byte) 70,         (byte) 73, 
        (byte) 67,         (byte) 65,         (byte) 84,         (byte) 69, 
        (byte) 42,         (byte) 42, 
    };
    
    byte[] msgSpUrlSig1SE = { 
        (byte) 209, 
        (byte) 2,         (byte) 124,         (byte) 83,         (byte) 112, 
        (byte) 145,         (byte) 1,         (byte) 26,         (byte) 85, 
        (byte) 0,         (byte) 104,         (byte) 116,         (byte) 116, 
        (byte) 112,         (byte) 58,         (byte) 47,         (byte) 47, 
        (byte) 119,         (byte) 119,         (byte) 119,         (byte) 46, 
        (byte) 109,         (byte) 97,         (byte) 114,         (byte) 107, 
        (byte) 117,         (byte) 115,         (byte) 112,         (byte) 97, 
        (byte) 103,         (byte) 101,         (byte) 46,         (byte) 99, 
        (byte) 111,         (byte) 109,         (byte) 89,         (byte) 3, 
        (byte) 86,         (byte) 1,         (byte) 83,         (byte) 105, 
        (byte) 103,         (byte) 9,         (byte) 1,         (byte) 1, 
        (byte) 0,         (byte) 64,         (byte) 86,         (byte) 127, 
        (byte) 150,         (byte) 229,         (byte) 135,         (byte) 114, 
        (byte) 168,         (byte) 153,         (byte) 162,         (byte) 241, 
        (byte) 144,         (byte) 195,         (byte) 57,         (byte) 19, 
        (byte) 39,         (byte) 177,         (byte) 211,         (byte) 81, 
        (byte) 199,         (byte) 31,         (byte) 27,         (byte) 56, 
        (byte) 211,         (byte) 14,         (byte) 114,         (byte) 172, 
        (byte) 69,         (byte) 2,         (byte) 30,         (byte) 187, 
        (byte) 15,         (byte) 90,         (byte) 13,         (byte) 150, 
        (byte) 243,         (byte) 166,         (byte) 177,         (byte) 236, 
        (byte) 34,         (byte) 4,         (byte) 111,         (byte) 224, 
        (byte) 62,         (byte) 255,         (byte) 48,         (byte) 213, 
        (byte) 254,         (byte) 227,         (byte) 69,         (byte) 32, 
        (byte) 9,         (byte) 121,         (byte) 93,         (byte) 49, 
        (byte) 240,         (byte) 98,         (byte) 78,         (byte) 116, 
        (byte) 199,         (byte) 85,         (byte) 228,         (byte) 228, 
        (byte) 194,         (byte) 201,         (byte) 1,         (byte) 0, 
        (byte) 15,         (byte) 42,         (byte) 42,         (byte) 67, 
        (byte) 69,         (byte) 82,         (byte) 84,         (byte) 73, 
        (byte) 70,         (byte) 73,         (byte) 67,         (byte) 65, 
        (byte) 84,         (byte) 69,         (byte) 42,         (byte) 42, 
    };
    
    private boolean midletPaused = false;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private Form form;
    private StringItem stringItem;
    //</editor-fold>//GEN-END:|fields|0|
    private DiscoveryManager dm;
    //</editor-fold>

    /**
     * The HelloMIDlet constructor.
     */
    public HelloMIDlet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        dm = DiscoveryManager.getInstance();
        try {
//            dm.addNDEFRecordListener(this, new NDEFRecordType(NDEFRecordType.NFC_FORUM_RTD, "urn:nfc:wkt:Sp"));
            dm.addTargetListener(this, TargetType.NDEF_TAG);
        } catch (ContactlessException ex) {
            ex.printStackTrace();
        }
        switchDisplayable(null, getForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|19-preAction
            if (command == exitCommand) {//GEN-END:|7-commandAction|1|19-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|2|19-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|7-postCommandAction
        }//GEN-END:|7-commandAction|3|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|4|
    //</editor-fold>//GEN-END:|7-commandAction|4|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|18-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            form = new Form("Record Writer", new Item[] { getStringItem() });//GEN-BEGIN:|14-getter|1|14-postInit
            form.addCommand(getExitCommand());
            form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return form;
    }
    //</editor-fold>//GEN-END:|14-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|16-getter|0|16-preInit
    /**
     * Returns an initiliazed instance of stringItem component.
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|16-getter|0|16-preInit
            // write pre-init user code here
            stringItem = new StringItem("Hello", "Hello, World!");//GEN-LINE:|16-getter|1|16-postInit
            // write post-init user code here
        }//GEN-BEGIN:|16-getter|2|
        return stringItem;
    }
    //</editor-fold>//GEN-END:|16-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
        if (dm != null) {
//            dm.removeNDEFRecordListener(this, new NDEFRecordType(NDEFRecordType.NFC_FORUM_RTD, "urn:nfc:wkt:Sp"));
            dm.removeTargetListener(this, TargetType.NDEF_TAG);
            System.out.println("Removed listeners");
        }
    }

    public void targetDetected(TargetProperties[] props) {
        System.out.println("targetDetected");
        form.append("targetDetected\n");
        if(props == null || props.length == 0) {
            form.append("No TargetProperties found!\n");
        }
        NDEFTagConnection conn = getNDEFTAGConnection(props);
        
        try {
                form.append("Creating new NDEFMessage...\n");
                
                NDEFMessage message = new NDEFMessage(msgSpUrlSig1, 0);
                form.append("Created NDEFMessage. Starting to write it.\n");
                conn.writeNDEF(message);
                form.append("NDEFMessage written.\n");
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
    
    public NDEFTagConnection getNDEFTAGConnection(TargetProperties[] tProp) {		
            for (int j = 0; j < tProp.length; j++) 
            {
                    Class[] connections = tProp[j].getConnectionNames();
                    if(connections != null)
                    {
                            for (int i = 0; i < connections.length; i++) 
                            {
                                    if (connections[i].getName().equals(
                                            "javax.microedition.contactless.ndef.NDEFTagConnection")) 
                                    {
                                            try 
                                            {
                                                    return (NDEFTagConnection) Connector.open(tProp[0]
                                                            .getUrl(connections[i]));
                                            } 
                                            catch (Exception e) 
                                            {
                                                    form.append(e.toString()+"\n");
                                                    System.out.println(e.toString() + "\n");
                                            }
                                    }
                            }
                    }
            }
            return null;		
    }

}
